package com.itheima.stock.service.impl;

import com.google.common.collect.Lists;
import com.itheima.stock.mapper.StockBusinessMapper;
import com.itheima.stock.mapper.StockMarketIndexInfoMapper;
import com.itheima.stock.mapper.StockRtInfoMapper;
import com.itheima.stock.pojo.StockMarketIndexInfo;
import com.itheima.stock.pojo.StockRtInfo;
import com.itheima.stock.service.StockTimerTaskServer;
import com.itheima.stock.utils.IdWorker;

import com.itheima.stock.utils.ParserStockInfoUtil;
import com.itheima.stock.vo.resp.StockInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ClassName StockTimerTaskServerImpl
 * @Description TODO
 * @date 2023/3/5 19:55
 * @Version 1.0
 */
@Slf4j
@Service
public class StockTimerTaskServerImpl implements StockTimerTaskServer {
    //注入格式解析bean
    @Autowired
    private ParserStockInfoUtil parserStockInfoUtil;

    @Autowired
    private StockBusinessMapper stockBusinessMapper;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private StockInfo stockInfo;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    StockRtInfoMapper stockRtInfoMapper;

    @Override
    public void getInnerMarkInfo() {
        String marketUrl = stockInfo.getMarketUrl();
        System.out.println(marketUrl);
        String innerUrl=marketUrl+String.join(",",stockInfo.getInner());
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Referer", "https://finance.sina.com.cn/stock/");
        HttpEntity http = new HttpEntity<String>(responseHeaders);

      ResponseEntity<String> exchange = restTemplate.exchange(innerUrl, HttpMethod.GET, http, String.class);
        String body = exchange.getBody();
        String[] split = body.split("\\n");
        ArrayList<StockMarketIndexInfo> stockMarketIndexInfos = new ArrayList<>();
        for (String s : split) {
            System.out.println(exchange);
            String reg="var hq_str_(.+)=\"(.+)\";";
            Pattern compile = Pattern.compile(reg);
            Matcher matcher = compile.matcher(s);
            String group1 = "";
            String group2 = "";
            String[] split1 = null;
            if (matcher.find()){
                 group1 = matcher.group(1);
                 group2 = matcher.group(2);
                split1 = group2.split(",");
            }
            StockMarketIndexInfo stockMarketIndexInfo = new StockMarketIndexInfo();
            stockMarketIndexInfo.setId(String.valueOf(idWorker.nextId()));
            //判断时间对时间进行处理
            stockMarketIndexInfo.setCurTime(new Date());
            stockMarketIndexInfo.setMarkId(group1);
            stockMarketIndexInfo.setMarkName(split1[0]);
            stockMarketIndexInfo.setCurPoint(new BigDecimal(split1[1]));
            stockMarketIndexInfo.setCurrentPrice(new BigDecimal(split1[2]));
            stockMarketIndexInfo.setUpdownRate(new BigDecimal(split1[3]));
            stockMarketIndexInfo.setTradeAccount( Long.parseLong(split1[4]));
            stockMarketIndexInfo.setTradeVolume( Long.parseLong(split1[5]));
            stockMarketIndexInfos.add(stockMarketIndexInfo);
        }
if(!stockMarketIndexInfos.isEmpty()){
    stockMarketIndexInfoMapper.insertList(stockMarketIndexInfos);

}


    }

    /**
     * 批量获取股票分时数据详情信息
     * http://hq.sinajs.cn/list=sz000002,sh600015
     */
    @Override
    public void getStockRtIndex() {
        //批量获取股票ID集合
        List<String> stockIds = stockBusinessMapper.getStockIds();
        //计算出符合sina命名规范的股票id数据
        stockIds = stockIds.stream().map(id -> {
            return id.startsWith("6") ? "sh" + id : "sz" + id;
        }).collect(Collectors.toList());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Referer","https://finance.sina.com.cn/stock/");
        headers.add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");
        HttpEntity<String> entity = new HttpEntity<>(headers);
//        大小为股票代码的数量
        Lists.partition(stockIds,stockIds.size()).forEach(list->{
            //拼接股票url地址
            String stockUrl=stockInfo.getMarketUrl()+String.join(",",list);
            //获取响应数据
            String result = restTemplate.postForObject(stockUrl,entity,String.class);
            List<StockRtInfo> infos = parserStockInfoUtil.parser4StockOrMarketInfo(result, 3);
            log.info("数据量：{}",infos.size());
            //TODO 批量插入

            stockRtInfoMapper.insertBatch(infos);
        });
    }
}
